import { unref } from 'vue'
import { isObject } from '@/utils/is'
import { cloneDeep } from 'lodash-es'
import { permissionStore } from '@/store/modules/permission'

// 取对象数组中属性组成纯数组
export function getSingleList(dataList: any[], prop: string) {
  const data: string[] = []
  dataList.forEach((item) => {
    data.push(item[prop])
  })
  return data
}

// 深度合并
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key])
  }
  return src
}

// dynamic use hook props
export function getDynamicProps<T, U>(props: T): Partial<U> {
  const ret: Recordable = {}

  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key])
  })

  return ret as Partial<U>
}

export function getPopupContainer(node?: HTMLElement): HTMLElement {
  return (node?.parentNode as HTMLElement) ?? document.body
}

export function toEleTreeData(
  data: any[],
  paramItem: any = { parentId: 'parentAuthorityId', id: 'authorityId' },
  rootValue: string = '0'
) {
  let list = cloneDeep(data)
  let treeData: any[] = [] // 新建数组 , 用来储存当前对象的子对象
  if (list && list.length) {
    list.forEach((item) => {
      // 遍历寻找子对象
      if (item[paramItem.parentId] === rootValue) {
        // 递归  返回对象的children列表
        const children = toEleTreeData(list, paramItem, item[paramItem.id])
        // 如果有children就将数组添加给对象
        if (children.length) {
          item.children = children
        }
        // 将完整的item添加给导出的数组
        treeData.push(item)
      }
    })
  }
  return treeData // 每次递归会返回当前的子列表
}
// 是否存在某个菜单权限
const deepMenuName = (dynamicRoutes: any[], menuName: string): any => {
  for (let i = 0; i < dynamicRoutes.length; i++) {
    if (dynamicRoutes[i].name === menuName) {
      return true
    } else if (dynamicRoutes[i].children) {
      if (deepMenuName(dynamicRoutes[i].children, menuName)) {
        return true
      }
    }
  }
  return false
}
export const systemUserAuth = (menuName: string) => {
  const { dynamicRoutes } = permissionStore()
  return deepMenuName(dynamicRoutes, menuName)
}
// 数字转换字符串
export const numTransString = (value: any) => {
  if (value === undefined || value === '' || value === null) {
    return null
  }
  return String(value)
}

// 筛选权限开通产品显示TODO
export const getFormatAuthList = (data: any[]) => {
  let arr = cloneDeep(data)
  let newArr: any[] = []
  arr.forEach((item: any) => {
    let dataObj = {
      ...item,
      items: []
    }
    item.items.forEach((items: any) => {
      if (items.isAuth === '1') {
        dataObj.items.push({ ...items })
      }
    })
    newArr.push(dataObj)
  })
  let resultArr: any[] = []
  newArr.forEach((item) => {
    if (item.items && item.items.length) {
      resultArr.push(item)
    }
  })
  return resultArr
}
// 设置权限勾选及时间属性
export const setPropAuthList = (data: any[]) => {
  if (data && data.length) {
    let arr = cloneDeep(data)
    let newArr: any[] = []
    arr.forEach((item: any) => {
      let dataObj = {
        ...item,
        items: []
      }
      item.items.forEach((items: any) => {
        dataObj.items.push({
          ...items,
          checked: items.isAuth === '1',
          disabled: items.isAuth === '1',
          timeRange: items.startDate && items.endDate ? [items.startDate, items.endDate] : []
        })
      })
      newArr.push(dataObj)
    })
    return newArr
  } else {
    return []
  }
}
// 获取勾选数据
export const getCheckAuthList = (data: any[]) => {
  if (data && data.length) {
    let arr = cloneDeep(data)
    let newArr: any[] = []
    for (let i = 0; i < arr.length; i++) {
      let dataObj: any = {
        appId: arr[i].appId,
        authList: []
      }
      let items = arr[i].items
      for (let j = 0; j < items.length; j++) {
        if (items[j].checked && (!items[j].timeRange || items[j].timeRange.length === 0)) {
          return {
            check: false,
            messageObj: {
              appName: arr[i].appName,
              authName: items[j].authName
            }
          }
        } else if (items[j].checked && items[j].timeRange && items[j].timeRange.length === 2) {
          dataObj.authList.push({
            authId: items[j].authId,
            authName: items[j].authName,
            tryFlag: 2,
            startDate: items[j].timeRange[0] + ' 00:00:00',
            endDate: items[j].timeRange[1] + ' 23:59:59'
            // startDate: items[j].timeRange[0],
            // endDate: items[j].timeRange[1]
          })
        }
      }
      newArr.push(dataObj)
    }
    let resultArr: any[] = []
    newArr.forEach((item) => {
      if (item.authList && item.authList.length) {
        resultArr.push(item)
      }
    })
    return {
      check: true,
      authList: resultArr
    }
  } else {
    return {
      check: true,
      authList: []
    }
  }
}

// 提交失败自动滚动到第一个错误字段TODO
export function scrollToFirstError(ele: any, blockValue: ScrollLogicalPosition = 'start') {
  try {
    let isError = ele.querySelectorAll('.ant-form-item-has-error')
    if (isError && isError.length) {
      isError[0].scrollIntoView({
        // 滚动到指定节点
        // 值有start,center,end，nearest，当前显示在视图区域中间
        block: blockValue,
        // 值有auto、instant,smooth，缓动动画（当前是慢速的）
        behavior: 'smooth'
      })
    }
  } catch (error) {
    console.info(error)
  }
}
// 字节转换
export function formatBytes(bytes: number | string | undefined, unit = 'MB') {
  if (!bytes) return `0 ${unit}`
  const k = 1024
  let bytesNum = Number(bytes)
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const i = Math.floor(Math.log(bytesNum) / Math.log(k))
  return (bytesNum / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
  // return (bytesNum / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

// 文档下载
export function downloadFile(url: string) {
  if (!url) return
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 格式化金额
export function formatMoney(value: string | number, decimal = 2) {
  if (!value) return '0.00'
  value = Number(value).toFixed(decimal).toString()
  const [integerPart, decimalPart] = value.split('.')
  return integerPart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + (decimal ? `.${decimalPart}` : '')
}

// 创建渠道树

// 该方法有缺陷，暂不使用
export function createChannelTree(data: any, parentCode: any) {
  let tree = []

  for (let obj of data) {
    if (obj.parentChannelCode === parentCode) {
      let children = createChannelTree(data, obj.channelCode)
      if (children.length && children.length > 0) {
        obj.children = children
      }
      tree.push(obj)
    }
  }

  return tree
}

export function transformToTree(data: any[]) {
  const tree: any[] = []
  const map = {} as any

  data.forEach((node) => {
    map[node.channelCode] = node
  })

  data.forEach((node) => {
    const parent = map[node.parentChannelCode]

    if (parent) {
      parent.children = parent.children || []
      parent.children.push(node)
    } else {
      node.parent = null
      tree.push(node)
    }
  })

  return tree
}
